package com.chuanzhi.recyclingmalladmin.filter;

import com.chuanzhi.recyclingmall.common.utils.JwtUtil;
import com.chuanzhi.recyclingmalladmin.po.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.http.SecurityHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
@Component
public class UserTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        获取请求头内的token，如果token为空则放行
        String token = request.getHeader("token");
        if (Objects.isNull(token)){
            filterChain.doFilter(request,response);
            return;
        }
//      通过token解析获取到sub内的sub
        String username = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();

        } catch (Exception e) {
            throw new RuntimeException("token异常");
        }
//        key从redis中获取登录时存放的loginUser信息
        String tokenKey = username+"token";
        LoginUser user = (LoginUser) redisTemplate.opsForValue().get(tokenKey);
        if (Objects.isNull(user)){throw new RuntimeException("token为空");}
//      将登录时的loginUser存放至SecurityContextHolder中退出登陆时可从SecurityContextHolder中拿到loginUser
//        ！！此处海差将用户权限放入UsernamePasswordAuthenticationToken的authorities中（后续权限访问时需补）
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
